package xin.marcher.wind.migrate.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import xin.marcher.wind.migrate.sharding.MigrateConfig;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 迁移代码相关数据源配置
 */
@Configuration
@MapperScan(basePackages = "xin.marcher.wind.migrate.mapper", sqlSessionTemplateRef = "migrateSqlSessionTemplate")
public class MigrateDataSourceConfig extends AbstractDataSourceConfig {

    @Resource
    private MigrateConfig migrateConfig;

    @Primary
    @Bean(name = "migrateDataSource")
    public DataSource dataSource() {
        // 构建本服务连接的数据源
        return buildDruidDataSource(migrateConfig.getMigrateDatasource());
    }

    @Primary
    @Bean(name = "migrateSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("migrateDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("xin.marcher.wind.migrate.domain");
        bean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/migrate/*.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean(name = "migrateTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("migrateDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "migrateSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("migrateSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
